/**
 * <p>Title: ServiceZMCM82.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张坤
 * @version 1.0
 * <pre>History:
 *          2010-12-17 下午01:33:45  张坤  Create
 *</pre>
 */
package com.baosight.sczx.zm.cm.service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.Utils;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.User;
import com.baosight.sczx.common.zm.cInterface.cm.ExportApplication;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialRation;
import com.baosight.sczx.common.zm.cInterface.cs.Engineering;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCM;
import com.baosight.sczx.zm.cm.domain.ZMCMExportApplication;
import com.baosight.sczx.zm.cm.domain.ZMCMExportApplicationDetail;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBasicInfo;

/**领料申请管理
 * <p>Title: ServiceZMCM82.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张坤
 * @version 1.0
 * <pre>History:
 *          2011-06-23 下午01:33:45  张坤  Create
 *</pre>
 */
public class ServiceZMCM82 extends ServiceEPBase {
	/**
	 * 初始数据管理从表页面初始化方法
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM82</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-06-23 下午01:35:45  张坤  Create
	 * </p>
	 *
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) 
	{
		inInfo.set("orgName", UserSession.getInSessionProperty("orgName"));//当前用户单位名
		inInfo.set("departmentId", UserSession.getInSessionProperty("orgCode"));
		inInfo.set("userName", UserSession.getInSessionProperty("UserCname"));//当前用户名
		String fdApplicationCode = queryfdCode();
		inInfo.set("fdApplicationCode",fdApplicationCode);
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		inInfo.addBlock(User.getInstance().getConstructionStaff(true));
		inInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.units"));
		inInfo.set("IsuseNoplanApplication",SystemSettingCM.getInstance().getIsuseNoplanApplication());

		return inInfo;
	}

	/**
	 * 根据年月查询部分领用的区队材料计划信息
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM82</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-07-08 上午09:38:45  张坤  Create
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	public EiInfo query(EiInfo inInfo) 
	{
		inInfo.getBlock("inqu_status").setCell(0, "fdPlanStatus", "已审核");
		EiInfo outInfo = new EiInfo();
		outInfo.addBlock(Utils.generateOutBlock(EiConstant.resultBlock, new ZMCMExportApplicationDetail(), inInfo, "ZMCMExportApplicationDetail.query1", false));
		
		Map<String, String> params = new HashMap<String, String>();

		params.put("fdYear", inInfo.getBlock("inqu_status").getCell(0, "fdYear").toString());
		params.put("fdMonth", inInfo.getBlock("inqu_status").getCell(0, "fdMonth").toString());	
		params.put("orgCode", inInfo.getBlock("inqu_status").getCell(0, "fdApplicationDepartment").toString());	
		params.put("fdApplicationDepartment", inInfo.getBlock("inqu_status").getCell(0, "fdApplicationDepartment").toString());	
		
		List<Map> result = MaterialRation.getMaterialRation("ZMCMMaterialRation.lessMoney", params);
		Double lessMoney= new Double(0);
		Double monthRation = new Double(0);
		if(result.size()>0)
		{
			monthRation = Double.valueOf(result.get(0).get("monthRation").toString());
			lessMoney = Double.valueOf(result.get(0).get("lessMoney").toString());
		}
		outInfo.set("lessMoney",lessMoney);//当前剩余额度
		List<Map> result1 = ExportApplication.getSUM("ZMCMExportApplication.allMoney", params);
		Double sum= new Double(0);
		if(result1.size()>0)
		{
			if(result1.get(0).get("sum") != null)
			{
				sum = Double.valueOf(result1.get(0).get("sum").toString());
			}
		}
		BigDecimal money = new BigDecimal(monthRation - sum);
		outInfo.set("Money", new DecimalFormat("0.00000").format(money));//当前剩额
		outInfo.addBlock(Engineering.getApplyProject("cmes.cm.applyProject", true));
		return outInfo;
	}
	
	/**
	 * 新增方法
	 * 新增从表数据
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM82</p>s
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-06-23 下午01:38:45  张坤  Create
	 * </p>
	 *
	 */
	@Override
	public EiInfo insert(EiInfo inInfo) 
	{
		//校验名称是否重复
		boolean validateValue = validate(inInfo, "ZMCMExportApplication.validate", new HashMap<String, String>());
		Double fdApplicationSum = 0.0;
		EiInfo outInfo = new EiInfo();
		EiInfo outInfo_up = null;
		if(validateValue) {
			return inInfo;
		}
		else
		{
			boolean validateStatus = validateNum(inInfo);
			if(validateStatus)
			{
				return inInfo;
			}
			else
			{
				outInfo_up = super.update(inInfo, "ZMCMTeammaterialplanDetail.updatefdStatusForNoCode");
				if(outInfo_up.getStatus() == -1)
				{
					outInfo.setStatus(-1);
					outInfo.setMsg(outInfo_up.getMsg());
					return outInfo;
				}
				
				String exportApplicationKeyId= TablePk.getInstance().getNextValue("T_CM_EXPORT_APPLICATION");
				inInfo.getBlock("inqu_status").setCell(0, "fdKeyId", exportApplicationKeyId);//主表主键
				outInfo = super.insert(inInfo, "ZMCMExportApplication.insert", "inqu_status");
				for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
				{
					inInfo.getBlock("result").setCell(i, "fdKeyId", TablePk.getInstance().getNextValue("T_CM_EXPORT_APPLICATION_DETAIL"));//从表主键
					inInfo.getBlock("result").setCell(i, "fdApplicationId", exportApplicationKeyId);
					
					Double sum = 0.0;
					Double fdApplicationNumber =  Double.valueOf(inInfo.getBlock("result").getCell(i, "fdApplicationNumber").toString());//获取个数
					inInfo.getBlock("result").setCell(i, "fdAuditNumber", fdApplicationNumber);//将申请数量一并赋给审批数量
					Double fdPrice =new Double(0);
					if(inInfo.getBlock("result").getCell(i, "fdPrice") != null)
						fdPrice=  Double.valueOf(inInfo.getBlock("result").getCell(i, "fdPrice").toString());//获取价格
					
					sum = fdApplicationNumber * fdPrice;
					fdApplicationSum = fdApplicationSum + sum;
					inInfo.getBlock("result").setCell(i, "fdApplicationSum", fdApplicationSum);
					inInfo.getBlock(EiConstant.resultBlock).setCell(i, "fdStatus", "部分");
				}

				outInfo = super.insert(inInfo, "ZMCMExportApplicationDetail.insert", "result");//插入从表数据
				
				if(outInfo.getStatus() == -1)
				{
					return outInfo;
				}
				
				outInfo_up = super.update(inInfo, "ZMCMTeammaterialplanDetail.updatefdApplicationExportNumForNoCode");// 更新已申请领用数量
				if(outInfo_up.getStatus() == -1)
				{
					outInfo.setStatus(-1);
					outInfo.setMsg(outInfo_up.getMsg());
					return outInfo;
				}
				
				outInfo_up = super.update(inInfo, "ZMCMExportApplication.applicationSum");//更新主表金额
				if(outInfo_up.getStatus() == -1)
				{
					outInfo.setStatus(-1);
					outInfo.setMsg(outInfo_up.getMsg());
					return outInfo;
				}

				return outInfo;
			}
		}
	}
	
	/**
	 * 在新增、修改操作时校验物资编码，名称不能重复
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-06-23 下午01:33:45  张坤  Create
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		params.put("fdApplicationCode", inInfo.getBlock("inqu_status").getCellStr(0, "fdApplicationCode"));

		List result = dao.query(sqlName, params);
		if(result!=null && result.size() > 0) {
			inInfo.setStatus(-1);
			inInfo.setMsg("领料单号不能重复！");
			return true;
		}
		return false;
	}
	
	/**
	 * 校验输入值
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-06-23 下午01:33:45  张坤  Create
	 * </p>
	 *
	 */
	private boolean validateNum(EiInfo inInfo) 
	{
		String fdPlanType = (inInfo.get("planType") == null)? "":inInfo.get("planType").toString();
		//剩余额度
		Double Money =  Double.valueOf(inInfo.get("Money").toString());
		//申请金额
		Double applicationMoney = new Double(0);
		
		for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
		{
			Object fdAN = inInfo.getBlock("result").getCell(i,"fdApplicationNumber");
			Double fdApplicationNumber    = (fdAN == null)? new Double(0):Double.valueOf(fdAN.toString());
            //申请数量
			Object fdEN = inInfo.getBlock("result").getCell(i,"fdExportedNumber");
            Double fdExportedNumber       = (fdEN == null)? new Double(0):Double.valueOf(fdEN.toString());
            //已发数量
            Object fdPN = inInfo.getBlock("result").getCell(i,"fdPurchaseNum");
            Double fdPurchaseNum          = (fdPN == null)? new Double(0):Double.valueOf(fdPN.toString());
            //需求数量
            Object fdAE = inInfo.getBlock("result").getCell(i,"fdApplicationExportNum");
            Double fdApplicationExportNum = (fdAE == null)? new Double(0):Double.valueOf(fdAE.toString());
            //已申请领用数量
            
            Object fdPE = inInfo.getBlock("result").getCell(i,"fdPrice");
            Double fdPrice = (fdPE == null)? new Double(0):Double.valueOf(fdPE.toString());
            
            //Object fdAP = inInfo.getBlock("result").getCell(i,"fdApplicationSum");
            //Double fdApplicationSum = (fdAP == null)? new Double(0):Double.valueOf(fdAP.toString());

            //申请金额 
            applicationMoney = applicationMoney + fdApplicationNumber*fdPrice;
        	BigDecimal data1 = new BigDecimal(fdApplicationNumber);
        	BigDecimal data2 = new BigDecimal(fdPurchaseNum - fdApplicationExportNum);
        	BigDecimal data3 = new BigDecimal(fdPurchaseNum - fdExportedNumber);
            if (!"无计划领用".equals(fdPlanType) && data1.compareTo(data2) > 0)
        	{
        		inInfo.setStatus(-1);
				inInfo.setMsg("申请数量不允许大于需求数量减去已申请数量！");
				return true;
        	}
            if (!"无计划领用".equals(fdPlanType) && data1.compareTo(data3) > 0)
        	{
        		inInfo.setStatus(-1);
				inInfo.setMsg("申请数量不允许大于需求数量减去已发数量！");
				return true;
        	}
        	if(!"无计划领用".equals(fdPlanType) && data1.compareTo(data3) < 0)
        	{
        		inInfo.getBlock("result").setCell(i, "fdStatus", "部分领用");
        	}
        	if(!"无计划领用".equals(fdPlanType) && data1.compareTo(data2)==0)
        	{
        		inInfo.getBlock("result").setCell(i, "fdStatus", "全部领用");
        	}
		}
		if(applicationMoney > Money)
		{
			inInfo.setStatus(-1);
			inInfo.setMsg("本次申请的金额已超过本单位本月剩余申请额度，重新填写领料申请明细或联系相关人员提高本月费用额度！");
			return true;
		}
		
		return false;
	}
	
	/**
	 * 明细customview 获取工程名
	 * <p>Function: queryforCustomview</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-21 上午09:30:43 张坤
	 * </p>
	 *
	 */
	public EiInfo getProjectName(EiInfo inInfo){         
		EiInfo outInfo = super.query(inInfo, "ZMCMExportApplication.queryProjectName",new ZMCMExportApplication());
		return outInfo;
	}
	
	/**
	 * 查询最新编号
	 * <p>Function: queryfdCode</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-7上午10:55:12 张坤
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String queryfdCode()
	{
		List<Map> _list = new ArrayList<Map>();
		HashMap	params = new HashMap<String, String>();
		String startStr = "LLSQ" + StaticTools.getDateDefault() + StaticTools.getTime().replaceAll(":", "");
		String defaultStr = startStr + "001";//定义格式
		_list = dao.query("ZMCMExportApplication.querySerialNum", params);
		if(_list!=null && _list.size() > 0) {
			String str = _list.get(0).get("fdNoteCode").toString();
			defaultStr = convertStr(startStr, str);
		}
		return defaultStr;
	}
	/**
	 * 构造编号
	 * <p>Function: convertStr</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-7上午10:52:36 张坤
	 * </p>
	 *
	 */
	private String convertStr(String startStr, String str)
	{
		String str1 = str.substring(18,21);//第二部分的流水号
		int nub = Integer.parseInt(str1); 
		str1 = Integer.toString(nub+1);
		if(str1.length() == 1){
			return startStr+"00"+str1;
		}else if (str1.length() == 2)
		{
			return startStr+"0"+str1;
		}else
		{
			return startStr+str1;
		}
	}
	
	public EiInfo queryforCustomview(EiInfo inInfo) 
	{
		StaticTools.setQueryParameters(inInfo, "fdMaterialStatus", "在用", true);
		EiInfo outInfo = super.query(inInfo, "ZMCMMaterialBasicInfo.query", new ZMCMMaterialBasicInfo());
		return outInfo;
	}
}
